import java.util.concurrent.Semaphore;

public class Demo3 {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        //初始化为4,表示有4个可用资源
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(() -> {
                System.out.println("申请资源");
                try {
                    semaphore.acquire();
                    System.out.println("申请到资源了");
                    Thread.sleep(1000);
                    System.out.println("释放资源了");
                    semaphore.release();
                } catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
}






